package cn.adkii.base.demo.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author malingdi
 * @description 反射demo
 * @date 2023/11/22 15:54
 */
public class ReflectDemo {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class cls = Class.forName("cn.adkii.base.demo.reflect.Student");
        // 打印字节码对象
        System.out.println(cls);
        System.out.println("===========打印构造方法============");
        // 打印结构方法名称
        System.out.println(cls.getDeclaredConstructor(String.class, Integer.class));
        Constructor[] constructors = cls.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName() + ";" + constructor.getModifiers() + ";" + constructor.getParameterTypes());
        }
        System.out.println("===============打印成员变量================");
        // 打印字段
        Field[] fields = cls.getFields();
        for (Field field : fields){
            System.out.println(field);
        }
        System.out.println("=======================打印方法============");
        // 打印方法
        Method[] methods = cls.getMethods();
        for (Method method : methods){
            System.out.println(method);
        }
        Constructor constructor = cls.getConstructor(String.class, Integer.class, Integer.class);
        Student student = (Student) constructor.newInstance("张三", 8, 2);
        System.out.println(student.getName() + ";" + student.getAge() + ";" + student.getSex());
        Field field = cls.getDeclaredField("name");
        field.setAccessible(true);
        field.set(student, "李四");
        System.out.println(student.getName() + ";" + student.getAge() + ";" + student.getSex());
        Method method = cls.getMethod("sayHi", String.class, Integer.class);
        System.out.println(method.invoke(student, "小王", 6));
    }
}
